package me.flyray.netty.feignserver;

import com.github.wxiaoqi.security.cache.CacheProvider;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.socket.SocketChannel;
import me.flyray.netty.handlers.NettyChannelMap;
import me.flyray.netty.handlers.ServerHandler;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: bolei
 * @date: 19:47 2018/10/29
 * @Description: 调用该接口获取收款二维码
 */

@Controller
@RequestMapping("/feign")
public class ReceivablesFeign {

    private static final Logger log = LoggerFactory.getLogger(ReceivablesFeign.class);

    @ResponseBody
    @RequestMapping(value = "getReceivablesQr", method = RequestMethod.POST)
    public Map<String, Object> getReceivablesQr(@RequestBody Map<String, Object> params) {
    	Map<String, Object> responseMap = new HashMap<String, Object>();
    	//接收参数
    	String number = (String)params.get("number");
    	String toAppParam = (String)params.get("toAppParam");
    	String[] words = toAppParam.split("\\|");
    	String orderId = words[0];

    	//传给我一个账号，根据账号获取该账号的二维码数据
        String str = null;
        //根据账号获取app的连接 channel 将w-lock 改成支付收款账号
        SocketChannel channel = NettyChannelMap.get(number);
        if (!StringUtils.isEmpty(channel)) {
            //
            //String toAppParam = 订单号|金额|二维码类型|收款账号
            ChannelFuture future = channel.writeAndFlush(toAppParam);
            //一直等该订单二维码是否生成，生成则返回，没有生成则一直等待
            //根据订单号获取redis中的数据 如果不存在则继续等待
            Integer count = 0;
            str = CacheProvider.get(orderId);
            while(StringUtils.isEmpty(str) && count < 10) {
                System.out.print("value of x : " + str );
                try {
                    Thread.sleep(1000);
                    count ++;
                    str = CacheProvider.get(orderId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //删除该订单号对应的二维码
            CacheProvider.del(orderId);
            //查询到数据则返回给前端
            responseMap.put("qrCode", str);
            responseMap.put("success", true);
            responseMap.put("code", "0000");
            responseMap.put("msg", "成功");
        }else{
        	responseMap.put("success", false);
            responseMap.put("code", "500");
            responseMap.put("msg", "失败");
        }
        return responseMap ;

    }

}
